#!/srv/newsblur/venv/newsblur3/bin/python

import datetime
import os
import sys

import boto
from boto.ec2.cloudwatch import CloudWatchConnection

from vendor.munin import MuninPlugin


class AWSCloudWatchELBRequestsPlugin(MuninPlugin):
    category = "AWS"
    args = "-l 0 --base 1000"
    vlabel = "Requests/sec"
    info = "Show number of requests per second"

    @property
    def title(self):
        return "Requests/sec for ELBs '%s'" % ",".join(self.elb_names)

    @property
    def fields(self):
        return [
            (n, dict(
                label = "requests on ELB %s" % n,
                type = "ABSOLUTE",
            )) for n in self.elb_names
        ]

    def __init__(self):
        self.api_key = os.environ['AWS_KEY']
        self.secret_key = os.environ['AWS_SECRET']
        self.elb_names = (sys.argv[0].rsplit('_', 1)[-1] or os.environ['ELB_NAME']).split(',')

    def execute(self):
        minutes = 5
        end_date = datetime.datetime.utcnow()
        start_date = end_date - datetime.timedelta(minutes=minutes)
        cw = CloudWatchConnection(self.api_key, self.secret_key)
        return dict(
            (n, sum(x['Sum'] for x in cw.get_metric_statistics(60, start_date, end_date, "RequestCount", "AWS/ELB", ["Sum"])))
            for n in self.elb_names
        )

if __name__ == "__main__":
    AWSCloudWatchELBRequestsPlugin().run()
